package com.labmi.experiment.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import sun.security.jca.GetInstance.Instance;

public class EntityManagerSingleton {

	
	private static EntityManager instance = null;
	private static String defaultPersistenceUnit;
	
	private EntityManagerSingleton()
	{
		
	}
	

	public static EntityManager getInstance() {
		return getInstance(defaultPersistenceUnit);
	}
	
	/**
	 * 
	 * @param persistenceUnit The name of persitence unit inside persistence.xml file
	 * @return
	 */
	public static EntityManager getInstance(String persistenceUnit)
	{
		if(instance == null || ! instance.isOpen())
		{
			defaultPersistenceUnit = persistenceUnit;
			
			java.util.Map<Object,Object> map = new java.util.HashMap<Object,Object>();
			EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit, map);
			instance = factory.createEntityManager(); 
		
		}
		
		return instance;
	}
	
//	public static EntityManager getNewInstance()
//	{
//		java.util.Map<Object,Object> map = new java.util.HashMap<Object,Object>();
//		EntityManagerFactory factory = Persistence.createEntityManagerFactory(defaultPersistenceUnit, map);
//		instance = factory.createEntityManager(); 
//		
//		return instance;
//	}

}
